/**
 * Triggers the edit mode when turned on.
 *
 * @type Boolean|Boolean
 */
var editMode = false;

/**
 * Some general options for the dragging and dropping of blocks.
 * @type Object
 */
var dragOptions = {
  grid: [5, 5],
  handle: 'strong',
  stop: saveBlockPosition
};

/*
 * Some general options for the dragging and dropping of
 * tabs
 * @type Object
 */
var pageSortOptions = {
  stop: savePageSort,
  cancel: '.dropdown,.divider-vertical'

};


/**
 * General options for the dragging and dropping of
 * links in blocks
 * @type Object
 */
var blockSortOptions = {
  stop: saveBlockSort,
};

/**
 * The blocks needed for the "add link" screen.
 * @type Array
 */
var blocks = new Array();

/**
 * Build the current page and add a trigger.
 */
$(document).ready(function() {
  buildPage(currentPage);
  $('#editMode').on('click', toggleEditMode);
});

/**
 * The main function that will build the page.
 * @param {int} pageID
 * @returns bool
 */
function buildPage(pageID) {
  /**
   * Remove current menu items.
   */
  $('ul.nav li[rel*="page-"]').remove();


  /**
   * Set a form element for the new-block form.
   */
  $('#new_block_page_id').val(pageID);

  /**
   * Empty the home screen.
   */
  $('#blocks').empty();

  /**
   * If the number of blocks is zero, we remove the "add link" menu-item.
   */

  if (allData.pagecount === 0) {
    $('li[rel="addBlock"]').remove();
  }

  /**
   * If the number of blocks is zero, we remove the "add link" menu-item
   */
  if (allData.blockcount === 0) {
    $('li[rel="addLink"]').remove();

  }

  /**
   * Loop over all pages.
   * @param {int} i
   * @param {Object} page
   */
  $.each(allData.pages, function(i, page) {
    /**
     * Create some list items (top menu)
     * @type @exp;@call;$@call;attr
     */
    var LI = $('<li>').attr('rel', 'page-' + page.id);
    var link = $('<a>').attr('href', '#').attr('rel', 'page-' + page.id).attr('title', page.title).text(page.title);
    LI.on('click', clickTab);
    LI.append(link);

    /**
     * Add edit-buttons to page links when editMode is true.
     * @type @exp;@call;$@pro;addClass@call;@call;on
     */
    if (editMode === true) {
      var eLink = $('<i>').addClass('icon-pencil').on('click', function() {
        editPage(page.id);
        return false;
      });
      link.append(' ');
      link.append(eLink);

      var delLink = $('<i>').addClass('icon-trash').on('click', function() {
        deletePage(page.id);
        return false;
      });
      link.append(' ');
      link.append(delLink);
    }

    /**
     * The active page gets another class.
     */
    if (page.id === pageID) {
      LI.addClass('active');
    }

    /**
     * Append it to the navigation.
     */
    LI.appendTo('ul.nav');

    /**
     * If this is the current page, create the blocks.
     */
    if (page.id === pageID) {

      /**
       * Clear out the select list for new-link
       */
      $('#block_id_select').empty();

      /**
       * Clear out the select list for edit-link
       */
      $('#edit_block_id select').empty();

      /**
       * Loop over each block
       * @param {int} j
       * @param {Object} block
       */
      $.each(page.blocks, function(j, block) {

        /**
         * Update the new-link form and edit-link form.
         */
        var opt = $('<option>').attr('label', block.title).attr('value', block.id).text(block.title);
        var opt2 = opt.clone(true);
        $('#block_id_select').append(opt);
        $('#edit_block_id select').append(opt2);

        /**
         * Create the actual block.
         */
        var bl = $('<div />').addClass('block').attr('id', 'block-' + block.id).draggable(dragOptions).css({top: block.y, left: block.x, position: 'absolute'});

        /**
         * Append the title of the block.
         */
        var title = $('<strong />').text(block.title);
        bl.append(title);

        /**
         * Edit mode?
         */
        if (editMode === true) {

          var delLink = $('<i>').addClass('icon-trash').on('click', function() {
            deleteBlock(block.id);
            return false;
          });
          title.append(' ');
          title.append(delLink);

          var eLink = $('<i>').addClass('icon-pencil').on('click', function() {
            editBlock(block.id);
            return false;
          });
          title.append(' ');
          title.append(eLink);
        }

        /**
         * Create an empty list for the links.
         */
        var list = $('<ul>');
        list.attr('rel', 'block-' + block.id);

        /**
         * Loop over the links and add them to the block.
         * @param {int} k
         * @param {Object} link
         */
        $.each(block.links, function(k, link) {
          /**
           * Create list item.
           */
          var li = $('<li>');
          li.attr('rel', 'linkli-' + link.id);

          /**
           * Create link.
           */
          var htmllink = $('<a>').attr('href', link.URL).text(link.title);

          /**
           * if edit mode, add nice drag-drop cursor to link.
           */
          if (editMode === true) {
            li.addClass('move');
          }

          /**
           * Append to list item.
           */
          list.append(li.append(htmllink));

          /**
           * In edit mode?
           */
          if (editMode === true) {
            var delLink = $('<i>').addClass('icon-trash').on('click', function() {
              deleteLink(link.id);
              return false;
            });
            li.append(' ');
            li.append(delLink);

            var eLink = $('<i>').addClass('icon-pencil').on('click', function() {
              editLink(link.id);
              return false;
            });
            li.append(' ');
            li.append(eLink);
          }
        });
        /**
         * If edit mode, make list sortable.
         */
        if (editMode === true) {
          list.sortable(blockSortOptions);
        }

        /**
         * Append list to block.
         */
        bl.append(list);

        /**
         * Append block to page.
         */
        bl.appendTo('#blocks');
      });
    }
  });

  /**
   * Make tabs on top sortable if in edit mode:
   */
  if (editMode === true) {
    $('ul.nav').sortable(pageSortOptions);

  }

  return true;
}

/**
 * Triggers the saving of a moved block.
 * @param {Object} event
 * @param {Object} ui
 * @returns {bool}
 */
function saveBlockPosition(event, ui) {
  $.post('block/drop', {
    x: ui.position.left,
    y: ui.position.top,
    id: $(event.target).attr('id').substring(6)
  },
  function(result) {
    // loop over the pages and blocks.
    // TODO:
    // get new allData
  }
  );
}

/**
 * Triggered when clicking on a tab.
 * @param {Object} e
 * @returns true
 */
function clickTab(e) {
  currentPage = parseInt($(e.target).attr('rel').substring(5));
  return buildPage(currentPage);
}

/**
 * Simple toggle function that switches between edit modes.
 * @returns bool
 */
function toggleEditMode() {
  editMode = editMode ? false : true;
  return buildPage(currentPage);
}

function editPage(id) {
  $.get('/page/info', {id: id}, function(page) {
    $('#editObject h3').text('Edit "' + page.title + '"');
    $('#editObject input[name="title"]').val(page.title);
    $('#editObject input[name="title"]').attr("placeholder", page.title);
    $('#editObject form').attr('action', '/page/edit');
    $('#editObject form input[name="id"]').val(id);

    $('#edit_url').hide();
    $('#edit_block_id').hide();
    $('#editObject').modal();
  });

}
function editBlock(id) {
  $.get('/block/info', {id: id}, function(block) {
    $('#editObject h3').text('Edit "' + block.title + '"')
    $('#editObject input[name="title"]').val(block.title);
    $('#editObject input[name="title"]').attr("placeholder", block.title);
    $('#editObject form').attr('action', '/block/edit');
    $('#editObject form input[name="id"]').val(id);

    $('#edit_url').hide();
    $('#edit_block_id').hide();
    $('#editObject').modal();
  });
}
function editLink(id) {
  $.get('/link/info', {id: id}, function(link) {
    $('#editObject h3').text('Edit "' + link.title + '"')
    $('#editObject input[name="title"]').val(link.title);
    $('#editObject input[name="title"]').attr("placeholder", link.title);
    $('#editObject input[name="url"]').val(link.URL);
    $('#editObject input[name="url"]').attr("placeholder", link.URL);
    $('#editObject form').attr('action', '/link/edit');
    $('#editObject form input[name="id"]').val(id);
    $('#edit_block_id select').val(link.block_id);
    $('#edit_url').show();
    $('#edit_block_id').show();
    $('#editObject').modal();
  });
}

function deletePage(id) {
  $.get('/page/info', {id: id}, function(page) {
    $('#object_type').text('tab');
    $('#object_name').text('"' + page.title + '"');
    $('#deleteObject h3').text('Delete "' + page.title + '"')
    $('#deleteObject form').attr('action', '/page/delete');
    $('#deleteObject form input[name="id"]').val(page.id);
    $('#deleteObject').modal();
  });
}

function deleteBlock(id) {
  $.get('/block/info', {id: id}, function(block) {
    $('#object_type').text('block');
    $('#object_name').text('"'+block.title+'"');
    $('#deleteObject h3').text('Delete "'+block.title+'"')
    $('#deleteObject form').attr('action', '/block/delete');
    $('#deleteObject form input[name="id"]').val(id);
    $('#deleteObject').modal();
  });
}

function deleteLink(id) {
  $.get('/link/info', {id: id}, function(link) {
  $('#object_type').text('link');
  $('#object_name').text('"'+link.title+'"');
  $('#deleteObject h3').text('Delete "'+link.title+'"')
  $('#deleteObject form').attr('action', '/link/delete');
  $('#deleteObject form input[name="id"]').val(link.id);
  $('#deleteObject').modal();
  });
}

function savePageSort(event, ui) {
  var order = 1;
  var total = $('ul.nav li[rel*="page-"]').length;
  var count = 0;
  $.each($('ul.nav li[rel*="page-"]'), function(i, page) {
    page = $(page);

    var pageID = page.attr('rel').substring(5);

    $.post('page/sort', {
      order: order,
      id: pageID
    }, function(data) {
      count++;
      // no response from server at the moment.
      if (count === total) {
        getNewData();
      }
    });
    order++;
  });
  ga('send', 'event', 'sort', 'page');
}

function saveBlockSort(event, ui) {
  var order = 1;
  var total = $(ui.item).parent().children().length;
  var blockID = $(ui.item).parent().attr('rel').substring(6);
  var count = 0;
  $.each($(ui.item).parent().children(), function(i, link) {
    link = $(link);

    var linkID = link.attr('rel').substring(7);
    $.post('link/sort', {
      order: order,
      id: linkID
    }, function(data) {
      count++;
      // no response from server at the moment.
      if (count === total) {
        getNewData();
      }
    });
    order++;
  });
  ga('send', 'event', 'sort', 'block');
}

function getNewData() {
  // grab new alldata var from server.
  $.get('/data', function(data) {
    allData = data;
  });
}